package com.azxcrm.common.utils.security;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;

import com.azxcrm.project.system.user.domain.User;

/**
 * shiro 工具类
 * 
 * @author Dustyone
 */
public class ShiroUtils
{

    public static Subject getSubjct()
    {
        return SecurityUtils.getSubject();
    }

    public static void logout()
    {
        getSubjct().logout();
    }

    public static User getUser()
    {
        return (User) getSubjct().getPrincipal();
    }

    public static void setUser(User user)
    {
        Subject subject = getSubjct();
        PrincipalCollection principalCollection = subject.getPrincipals();
        String realmName = principalCollection.getRealmNames().iterator().next();
        PrincipalCollection newPrincipalCollection = new SimplePrincipalCollection(user, realmName);
        // 重新加载Principal
        subject.runAs(newPrincipalCollection);
    }
    
    /**
     * 校验角色是否存在
     * @param roleName
     * @return
     */
    public static boolean hasRole(String roleName) {
    	Subject subject = SecurityUtils.getSubject();
    	if(subject.hasRole(roleName)) {
    		return true;
    	}else {
    		return false;
    	}
    }
    
    /**
     * 校验用户是否拥有某角色
     * @param rolesNames
     * @return
     */
	public static boolean hasRoles(List<String> rolesNames) {
		Subject subject = SecurityUtils.getSubject();
		for (String roleName : rolesNames) {
			if (subject.hasRole(roleName)) {
				return true;
			}
		}
		return false;
	}
    

    public static Long getUserId()
    {
        return getUser().getUserId().longValue();
    }
    
    /**
     * 获取Shiro缓存中的用户名
     * @return 用户名
     */
    public static String getUserName()
    {
        return getUser().getUserName();
    }

    public static String getLoginName()
    {
        return getUser().getLoginName();
    }

    public static String getIp()
    {
        return getSubjct().getSession().getHost();
    }
    
    /**
     * 获取Shiro中的用户登录来源
     * @return
     */
    public static String getLoingSource(){
    	return getUser().getLoginSource();
    }
    
    public static String getSessionId()
    {
        return String.valueOf(getSubjct().getSession().getId());
    }
}
